package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.constant.enums.ResultEnum;
import com.example.demo.exception.CustomException;
import com.example.demo.form.User.AddUserForm;
import com.example.demo.form.User.ListUserForm;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.entity.User;
import com.example.demo.model.vo.PageVo;
import com.example.demo.model.vo.UserVo;
import com.example.demo.service.IUserService;
import com.example.demo.utils.MethodUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author: LKP
 * @create: 2020/11/25
 * @Description:
 * @FileName: TestServiceImpl
 * @History:
 * @自定义内容：
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    final UserMapper userMapper;

    /**
     * 根据用户名获取用户信息
     *
     * @param name 用户名
     * @return 用户信息
     */
    @Override
    public String getUserByName(String name) {
        User user = userMapper.getUserByName(name);
        return (user == null) ? "没有该用戶" : user.toString();
    }

    /**
     * 添加用户
     *
     * @param userForm 用户表单数据
     * @return 成功或者失败
     */
    @Override
    public boolean addUser(AddUserForm userForm) {
        return save(userForm.buildEntity());
    }

    @Override
    public PageVo<UserVo> listUser(ListUserForm listUserForm) {
        PageVo<UserVo> pageVo = new PageVo<UserVo>().setCurrentAndSize(listUserForm);
        pageVo.setTotal(countUser());
        pageVo.setRecords(userMapper.listUser(listUserForm.calcCurrent()));
        return pageVo;
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteUser(int id) {
        // 如果删除失败抛出异常
        if (!removeById(id)) {
            // 仅做测试全局异常演示，不推荐这样干
            throw new CustomException(ResultEnum.DELETE_ERROR, MethodUtil.getLineInfo());
        }
        return true;
    }

    /**
     * 获取用户数量
     *
     * @return
     */
    private Integer countUser() {
        return count(new QueryWrapper<User>());
    }
}
